package io.renren.api;

import io.renren.entity.WxUser;
import io.renren.service.WxUserService;
import io.renren.utils.ConfigConstant;
import io.renren.utils.Constant;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/api/wechat")
public class ApiWechatAuthController {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WxUserService wxUserService;

    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl) {
        String url = ConfigConstant.BASE_URL + "/api/wechat/userInfo";
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        log.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        return "redirect:" + redirectURL;
    }

    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code, @RequestParam("state") String returnUrl, HttpSession httpSession) throws Exception {
        log.info("【微信网页授权】code={}", code);
        log.info("【微信网页授权】state={}", returnUrl);
        WxMpUser wxMpUser;
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        try {
            wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, "zh_CN");
        } catch (WxErrorException e) {
            log.info("微信授权，第一次出现错误,{}", e.getError().getErrorMsg());
            if (e.getError().getErrorCode() == -1) {
                try {
                    wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, "zh_CN");
                } catch (WxErrorException e1) {
                    log.info("微信授权，第二次出现错误,{}", e.getError().getErrorMsg());
                    throw new Exception(e1.getError().getErrorMsg());
                }
            } else {
                log.info("【微信网页授权】{}", e);
                throw new Exception(e.getError().getErrorMsg());
            }
        }

        //去微信后台获取信息
        WxMpUser wxMpUser1 = wxMpService.getUserService().userInfo(wxMpUser.getOpenId());

        log.info("【微信网页授权】openId={}", wxMpUser.getOpenId());
        //验证用户，并且保存到session中
        //查询用户是否存在，如果不存在则保存，如果存在则更新
        HashMap<String, Object> map = new HashMap<>();
        // map.put("openId", wxMpUser.getOpenId());
        map.put("unionId", wxMpUser.getUnionId());
        List<WxUser> wxUsers = wxUserService.queryList(map);
        WxUser wxUser = null;
        if (wxUsers == null || wxUsers.size() == 0) {
            wxUser = new WxUser();
            wxUser.setOpenId(wxMpUser.getOpenId());
            wxUser.setStatus("0");
            if (wxMpUser1 != null && wxMpUser1.getSubscribe()) {
                wxUser.setSubscribe("1");
                wxUser.setSubscribeScene(wxMpUser1.getSubscribeScene());
                wxUser.setSubscribeTime(new Date(wxMpUser1.getSubscribeTime() * 1000));
                wxUser.setQrSceneStr("0".equals(wxMpUser1.getQrScene()) ? wxMpUser1.getQrSceneStr() : wxMpUser1.getQrScene());
            } else {
                wxUser.setSubscribe("0");
            }
            wxUser.setUnionId(wxMpUser.getUnionId());
            wxUser.setImgUrl(wxMpUser.getHeadImgUrl());
            wxUser.setGradeId(Long.parseLong(ConfigConstant.DEFAULT_GRADE_ID));
            wxUser.setNickName(wxMpUser.getNickname());
            wxUserService.save(wxUser);
            log.info("保存用户信息 wxUser=" + wxUser);
        } else {
            wxUser = wxUsers.get(0);
            if (wxMpUser1 != null && wxMpUser1.getSubscribe()) {
                wxUser.setSubscribe("1");
                wxUser.setSubscribeScene(wxMpUser1.getSubscribeScene());
                wxUser.setSubscribeTime(new Date(wxMpUser1.getSubscribeTime() * 1000));
                wxUser.setQrSceneStr("0".equals(wxMpUser1.getQrScene()) ? wxMpUser1.getQrSceneStr() : wxMpUser1.getQrScene());
            }
            wxUser.setUpdateTime(new Date());
            wxUser.setOpenId(wxMpUser.getOpenId());
            wxUser.setImgUrl(wxMpUser.getHeadImgUrl());
            wxUser.setNickName(wxMpUser.getNickname());
            wxUserService.update(wxUser);
            log.info("更新用户信息 wxUser=" + wxUser);
        }
        httpSession.setAttribute(Constant.SESSION_USER_KEY, wxUser);
        log.info("将用户信息保存到session中并且重定向到指定的路径 url=" + returnUrl);
        return "redirect:" + returnUrl;
    }

}
